import moment from 'moment'

// import parseTime, formatTime and set to filter

export { parseTime, formatTime } from '@/utils'

import Vue from 'vue'

export function camelize(str, prefix = 'as') {
  var reg = /[_|-|\.](\w)/g
  var camelString = str.replace(reg, (a, b) => {
    return b.toUpperCase()
  })
  if (prefix) {
    return prefix + camelString.replace(/(\w)/, v => v.toUpperCase())
  }
  return camelString
}

const path = require('path')
const filters = {}
const formats = require.context('./formats', false, /\.js$/)

formats.keys().forEach(key => {
  const module = formats(key).default
  if (module !== undefined) {
    var name = path.basename(key, '.js')
    filters[name] = module
    Vue.filter(`${camelize(name)}`, module)
  }
})

function $filterLoader() {
  for (
    var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 0;
    _key < _len;
    _key++
  ) {
    args[_key] = arguments[_key]
  }
  args.reverse()
  if (args.length < 2) {
    return
  }
  var name = args.shift()
  if (!name) {
    return
  }
  var fn = filters[name]
  if (!fn) {
    return
  }
  return fn.apply(this, args)
}
Vue.filter('formatter', $filterLoader)

/**
 * Show plural label if time is plural number
 * @param {number} time
 * @param {string} label
 * @return {string}
 */
function pluralize(time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

/**
 * @param {number} time
 */
export function parseTimeMixed(time) {
  var datetime = moment(time * 1000)
  return datetime.format('l LTS')
}

/**
 * @param {number} time
 */
export function timeAgo(time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}

/**
 * Number formatting
 * like 10000 => 10k
 * @param {number} num
 * @param {number} digits
 */
export function numberFormatter(num, digits) {
  const si = [
    { value: 1e18, symbol: 'E' },
    { value: 1e15, symbol: 'P' },
    { value: 1e12, symbol: 'T' },
    { value: 1e9, symbol: 'G' },
    { value: 1e6, symbol: 'M' },
    { value: 1e3, symbol: 'k' }
  ]
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (
        (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
      )
    }
  }
  return num.toString()
}

/**
 * Upper case first char
 * @param {String} string
 */
export function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}
